<?php

namespace Product\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Product\Form\ProductForm;
use Product\Form\Filter\ProductFilter;
use Product\Model\Product;
use Zend\Filter\File\RenameUpload;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Null as PageNull;

use Zend\Validator\File\Size;
use Zend\Validator\File\IsImage;
use Zend\Validator\File\MimeType;
use Zend\Form\Element;
use Zend\Validator\File\Count;
use Zend\Math\Rand;
use Zend\View\View;

use Imagine\Gd\Imagine;

class IndexController extends HeadController
{
	protected $ProductTable;
	protected $ProductTypeTable;
	protected $ImgProductTable;
	protected $Imagine;
	
    public function indexAction()
    {	
    	//get action , controller..$getjquest  = $this->getEvent()->getRouteMatch()->getParams();
    	/* $renderer = $this->getServiceLocator()->get('Zend\View\Renderer\PhpRenderer');
    	$renderer->headTitle('Đây là title');
    	$renderer->headMeta()->appendName('keywords', 'đây,là,các,keywords');
    	$renderer->headMeta()->appendName('description', 'Đây là description');
    	$renderer->headScript()->appendFile('/public/template/product/js/product.js'); */    
    	$this -> headsAction();
    	
    	$this->layout('layout/backend');
    	$request = $this->getRequest();
    	$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    	$form = new ProductForm(null,$dbAdapter);
    	$form->setInputFilter(new ProductFilter($dbAdapter) );
    	if($request->isPost()){   		 
    		$data = $request->getPost();   	
    		$this->redirect()->toUrl('/product/search_by/'.$data->nameprosearch);
    	}	
    	$search = $this->params()->fromRoute('search_by');
    	$itemsPerPage = 10;
    	$pageRange = 5;
    	$page = $this->params()->fromRoute('page', 1);
    	$offset = ($page - 1) * $itemsPerPage;
    	
    	$urlhientai = $this->request->getRequestUri();
    	$mahoa = md5($urlhientai);
    	if(!empty($search)){
    		
    		$allRecord = $this->getProductTable()->countSearchAll($search);
    		$listproduct = $this->getProductTable()->fetchSearchAll($offset, $itemsPerPage,$search,$mahoa);
    	}else {
           $allRecord = $this->getProductTable()->countAll();
           $listproduct = $this->getProductTable()->fetchAll($offset, $itemsPerPage,$mahoa);
    	}
    	$pageNull = new PageNull($allRecord);
    	$paginator = new Paginator($pageNull);
    	$paginator->setCurrentPageNumber($page);
    	$paginator->setItemCountPerPage($itemsPerPage);
    	$paginator->setPageRange($pageRange);
    	   	
    	foreach ($listproduct as $val)
    	     $this->imageAction(UPLOAD_PATH.'/product/'.$val['LINKIMG'],$val['LINKIMG'],120,100);
    	
        return new ViewModel(array(
                'product' => $listproduct,
        		'paginator' => $paginator,
        		'allRecord' => $allRecord,
        		'offset' => $offset,
        		'itemsPerPage' => $itemsPerPage,
        		'SearchForm' => $form,
        		'search_by'  => $search
         ));
        
    }
    
    public function deletetimthumbAction(){
    	$this->delete_dir(APPLICATION_PATH.'/timthumb');
    	return $this->redirect()->toRoute('product');
    }
    
    public function deletecacheAction(){
    	$this->delete_dir(APPLICATION_PATH.'/data/cache/cache_data');
    	return $this->redirect()->toRoute('product');
    }
    
    function delete_dir($src) {
    	$dir = opendir($src);
    	while(false !== ( $file = readdir($dir)) ) {
    		if (( $file != '.' ) && ( $file != '..' )) {
    			if ( is_dir($src . '/' . $file) ) {
    				$this->delete_dir($src . '/' . $file);
    			}
    			else {
    				unlink($src . '/' . $file);
    			}
    		}
    	}
    	rmdir($src);
    	closedir($dir);
    }
    
    public function imageAction($destinationPath,$timthumb,$width, $height)
    {
    	$imagine = $this->getImagineService();
    	$size = new \Imagine\Image\Box($width, $height);
    	$mode = \Imagine\Image\ImageInterface::FILTER_UNDEFINED;
    
    	$image = $imagine->open($destinationPath);
    	$structure = APPLICATION_PATH.'/timthumb/'.$width.'x'.$height;
    	if (!is_dir($structure))
    	   mkdir($structure, 0777, true);
    	$image->resize($size, $mode)->save($structure.'/'.$timthumb);
    }
    
    public function getImagineService()
    {
    	if ($this->Imagine === null)
    	{
    		$this->Imagine = $this->getServiceLocator()->get('image_service');
    	}
    	return $this->Imagine;
    }
    
    public function highlightsAction(){
    	$id = (int) $this->params()->fromRoute('id', 0);
    	$idquery = (string) $this->params()->fromQuery('noibat');
    	$this->getProductTable()->updatehighlights($id,$idquery);   	
    	$this->redirect()->toUrl($this->getRequest()->getServer('HTTP_REFERER'));
    }

    
    public function addAction(){
    	$this -> headsAction();
    	$this->layout('layout/backend');
    	//Khởi tạo đối tượng ProductForm
    	$request = $this->getRequest();
    	$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    	$form = new ProductForm(null,$dbAdapter); 
    	$form->setInputFilter(new ProductFilter($dbAdapter) );
    	if($request->isPost()){
    		$files = $request->getFiles()->toArray();
    		$data = $request->getPost();
    		$form->setData($data);
    		$product = new Product();
    		if($form->isValid()){
    			$adapter  = new \Zend\File\Transfer\Adapter\Http();
    			/* Nếu bạn đang sử dụng XAMPP và localhost chỉ cần mở file php.ini của bạn và bỏ ghi chú:  			
    			extension = php_fileinfo.dll hoặc trên hosting thì vào Select PHP Version chọn fileinfo -> MimeType mới chạy 
    			in data trong ckeditor ra html thì <?php echo $product->CONTENT_PR;?> ko có escapeHtml
    			*/
    			$typefileupload = new MimeType(array('image/jpeg','image/jpg','image/png','image/gif',));   
    			$size = new Size(array('max'=>512000));
    			 $typefileupload->setMessages(array(MimeType::FALSE_TYPE =>'File không hợp lệ ! (png,jpg,jpeg,gif)'));
    			$size->setMessages(array(Size::TOO_BIG =>'Dung lượng file upload lớn nhất là %max% nhưng file được chọn %size% !'));
    			$adapter->setValidators(array($size,$typefileupload));
    			if (!$adapter->isValid()){
    				 
    				$dataError = $adapter->getMessages();
    				$error = array();
    				foreach($dataError as $key=>$row)
    				{
    					if ($key == 'fileUploadErrorNoFile')
    						$error[] = 'File upload không để trống !';
    					else 
    					   $error[] = $row;
    				}
    				$form->setMessages(array('file_uploads'=>$error ));
    			}else {
    			$product->addArray($data);
    			$val_id_product = $this->getProductTable()->saveProduct($product,0);
    			$arrfilename = $this->upload($files,UPLOAD_PATH.'/product');
    			$this->getImgProductTable()->saveImgProduct($arrfilename,$val_id_product);    			
    			// Redirect to list of product
    			return $this->redirect()->toRoute('product');
    			}
    		}
    	};    	
    	
    	//Truyền đối tượng UserForm vào đối tượng ProductForm
    	$viewModel  = new ViewModel(array(
    			                'ProductForm' => $form,
    			                //'producttype' => $this->getProductTypeTable()->fetchAll(),
    	));	 
    	//Đưa đối tượng ViewModel ra ngoài VIEW
    	return $viewModel;
    }
     
    
    public function editAction(){
    	$this->layout('layout/backend');
    	
    	$id = (int) $this->params()->fromRoute('id', 0);
    	
    	if (!$id) {
    		return $this->redirect()->toRoute('product', array(
    				'action' => 'add'
    		));
    	}else{   	
    		//get url hien tai var_dump($this->request->getRequestUri());die;    		    	
    	
    	$product = $this->getProductTable ()->getProduct ( $id );
    	$imgproduct = $this->getImgProductTable ()->getImgProduct ( $id );
    	if(empty($product) || empty($imgproduct)){
    		 return $this->notFoundAction ();
    	}else{ 
    		$urlhientai = $this->request->getRequestUri();
    		$url = '/product/edit/'.$id.'-'.$this->vn2latin($product->NAME_PR,true).'.html';
    		if($urlhientai != $url)
    			$this->redirect()->toUrl($url);
	    	$request = $this->getRequest();
	    	$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
	    	$form = new ProductForm(null,$dbAdapter);
	    	$form->setInputFilter(new ProductFilter($dbAdapter) );
	    	$form->bind ( $product );
	    	
	    	foreach ($imgproduct as $val)
	    	   $this->imageAction(UPLOAD_PATH.'/product/'.$val->LINKIMG,$val->LINKIMG,870,300);
	    	foreach ($imgproduct as $val)
	    		$this->imageAction(UPLOAD_PATH.'/product/'.$val->LINKIMG,$val->LINKIMG,62,62);
	    	//Truyền đối tượng UserForm vào đối tượng ProductForm
	    	$viewModel  = new ViewModel(array(
	    			'ProductForm' => $form,
	    			'imgproduct'  => $imgproduct,
	    	));
	    	$this -> headsAction($product->NAME_PR);
	    	if($request->isPost()){
	    		$files = $request->getFiles()->toArray();
	    		$data = $request->getPost();
	    	
	    		$form->setData($data);
	    		$product = new Product();
	    		if($form->isValid()){
	    			        $adapter  = new \Zend\File\Transfer\Adapter\Http();
	    			        $typefileupload = new MimeType(array('image/jpeg','image/jpg','image/png','image/gif',));
	    			 		$size = new Size(array('max'=>512000));
	    			 		$typefileupload->setMessages(array(MimeType::FALSE_TYPE =>'File không hợp lệ ! (png,jpg,jpeg,gif)'));
    			            $size->setMessages(array(Size::TOO_BIG =>'Dung lượng file upload lớn nhất là %max% nhưng file được chọn %size% !'));
    			            $adapter->setValidators(array($size,$typefileupload));
    			            foreach ($files as $imgval){
    			             if (!empty($imgval['name'])){
	    	    			   if (!$adapter->isValid()){
			    	    			$dataError = $adapter->getMessages();
			    	    			$error = array();
			    	    			foreach($dataError as $key=>$row)
			    	    			{
		    					       $error[] = $row;
			    	    			}
			    	    			$form->setMessages(array('file_uploads'=>$error ));
	    		          	     }else{
		    			            $product->addArray($data);
			    	    			$val_id_product = $this->getProductTable()->saveProduct($product,$id);
			    	    			$arrfilename = $this->upload($files,UPLOAD_PATH.'/product');
			    	    			$this->getImgProductTable()->saveImgProduct($arrfilename,$id);			    	    			 
			    	    			// Redirect to list of product
			    			        return $this->redirect()->toRoute('product');
	    	    			       }
    			                }else{
    			                	$product->addArray($data);
    			                	$val_id_product = $this->getProductTable()->saveProduct($product,$id);    			                	
    			                	// Redirect to list of product
    			                	return $this->redirect()->toRoute('product');
    			                  } 
    			                }
	    	    			}
	    	    		};
	    	    		
				    	//Đưa đối tượng ViewModel ra ngoài VIEW
				    	return $viewModel;
    	  }
    	}
    }
    
    public function upload($files = array(),$file_path = null){
    	if(count($files) != 0 && $file_path != null){
    
    		$uploadObj = new \Zend\File\Transfer\Adapter\Http();
    		$uploadObj->setDestination($file_path);
    		$arr_filename = array();
    		foreach ($files as $key => $val){
    			$filename = date('Y').'_'.date('m').'_'.date('d').'_'.Rand::getInteger(0,99999999).'_'.$val['name'];
    			$arr_filename[] = $filename;
    			$dv = $uploadObj->addFilter('Rename',
    					array('target' => $file_path.'/'.$filename,
    							'overwrite' => true),'file1');
    			$uploadObj->receive($key);
    		}
    	}
    	return $arr_filename;
    }
    
    public function tetAction()
    {
    	$this->layout('layout/backend');
    	return new ViewModel(array(
    			'footers' =>'hfg'
    	));
    
    }
    
    public function deleteAction()
    {
    	$id = $this->params()->fromRoute('id');
    	$getimg =$this->getImgProductTable()->getImgProduct($id);
    	foreach ($getimg as $val){
    	$image = UPLOAD_PATH.'/product/' . $val->LINKIMG;
    	if (file_exists ( $image ) == true){
    		unlink ( $image );
    	}  		
      }
      $this->getProductTable()->deleteProduct($id);
      $this->getImgProductTable()->deleteImgProduct($id);
      return $this->redirect()->toRoute('product');
    }
    
    public function deleteAllAction()
    {
    	$arrid = $this->params()->fromRoute('id');
    	 $arrstr = explode(',',$arrid ) ;
    	 
    	 $getimg =$this->getImgProductTable()->getAllImgProduct($arrstr);
    	 
    	 foreach ($getimg as $val){
    	 	$image = UPLOAD_PATH.'/product/' . $val->LINKIMG;
    	 	if (file_exists ( $image ) == true){
    	 		unlink ( $image );
    	 	}
    	 };
    	 
    	$this->getProductTable()->deleteAllProduct($arrstr);
    	$this->getImgProductTable()->deleteAllImgProduct($arrstr);
    	return $this->redirect()->toRoute('product');
    }
    
    public function getProductTable()
    {
    	if (!$this->ProductTable) {
    		$sm = $this->getServiceLocator();
    		$this->ProductTable = $sm->get('Product\Model\ProductTable');
    	}
    	return $this->ProductTable;
    }
    
    public function getImgProductTable()
    {
    	if (!$this->ImgProductTable) {
    		$sm = $this->getServiceLocator();
    		$this->ImgProductTable = $sm->get('Product\Model\ImgProductTable');
    	}
    	return $this->ImgProductTable;
    }
    
    /* định dạng chuỗi nhập
     tham số $tolower, true nếu bạn muốn nhận chuỗi không dấu dưới dạng viết thường,
     false sẽ trả về chữ không dấu còn viết hoa hay viết thường thì duy trì như chuỗi ban đầu đưa vào. */
    function vn2latin($str, $tolower = false)
    {
    		$str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
			$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
			$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
			$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
			$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
			$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
			$str = preg_replace("/(đ)/", 'd', $str);
			$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
			$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
			$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
			$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
			$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
			$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
			$str = preg_replace("/(Đ)/", 'D', $str);
		   $str = preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'),
		   		array('', '-', ''), $str);
    	if ($tolower) {
    		return strtolower($str);
    	}
    
    	return $str;
    
    }
}
